package com.zxy.ziems.server.device.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.zxy.ziems.server.device.convertor.DeviceConvertor;
import com.zxy.ziems.server.device.mapper.ProtocolMapper;
import com.zxy.ziems.server.device.pojo.dto.ProtocolDTO;
import com.zxy.ziems.server.device.pojo.entity.CollectorEntity;
import com.zxy.ziems.server.device.pojo.entity.ProtocolEntity;
import com.zxy.ziems.server.device.pojo.vo.ProtocolVO;
import com.zxy.ziems.server.device.service.ProtocolService;
import com.zxy.ziems.server.mybatis.core.service.ServiceImplX;
import com.zxy.ziems.server.utils.AssertUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 协议管理
 * @author 10348359
 * @create 2024-03-25 13:17
 */
@Service
public class ProtocolServiceImpl extends ServiceImplX<ProtocolMapper, ProtocolEntity> implements ProtocolService {

    @Override
    public void add(ProtocolDTO dto) {
        AssertUtil.isNull(getByCode(dto.getCode()), "编码重复");
        ProtocolEntity entity = DeviceConvertor.INSTANCE.protocolDTOConvert2DO(dto);
        save(entity);
    }

    @Override
    public void update(ProtocolDTO dto) {
        AssertUtil.nonNull(getById(dto.getId()), "数据单位不存在");
        ProtocolEntity old = getByCode(dto.getCode());
        AssertUtil.isTrue(Objects.isNull(old) || old.getId().equals(dto.getId()), "编码重复");
        ProtocolEntity entity = DeviceConvertor.INSTANCE.protocolDTOConvert2DO(dto);
        updateById(entity);
    }

    @Override
    public void deleteById(String id) {
        if (StrUtil.isBlank(id)) {
            return;
        }
        removeById(id);
    }

    @Override
    public ProtocolEntity getByCode(String code) {
        return getOne(ProtocolEntity::getCode, code);
    }


    @Override
    public ProtocolEntity getById(String id) {
        return super.getById(id);
    }

    @Override
    public ProtocolEntity getByChannelId(String channelId) {
        if (StrUtil.isBlank(channelId)) {
            return null;
        }
        return baseMapper.selectByChannelId(channelId);
    }

    @Override
    public List<ProtocolEntity> listByIdList(Collection<String> idList) {
        return super.listByIds(idList);
    }

    @Override
    public List<ProtocolEntity> listByChannelId(Collection<String> channelIdList) {
        if (CollectionUtil.isEmpty(channelIdList)) {
            return new ArrayList<>(0);
        }
        return baseMapper.selectByChannelIdList(channelIdList);
    }

    @Override
    public List<ProtocolVO> viewList() {
        List<ProtocolEntity> list = list();
        return DeviceConvertor.INSTANCE.protocolDOListConvert2VOList(list);
    }
}
